import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { Button, Input, InputNumber, Pagination, Tooltip, Upload } from 'antd';
import _ from 'lodash';
import { useTablePipeline } from 'ali-react-table';
// @ts-ignore
import { CheckCircleOutlined, CloseCircleOutlined } from '#/utils/antdIcons';
import { AntdBaseTable } from '@/base/TBaseTable';
import type { IDataSourceType } from '../../type';
import styles from './index.less';
import { DeleteOutlined, DownloadOutlined } from '@ant-design/icons';
import {
  deleteMonthTableDataService,
  monthTableRowEditService,
  saveMonthTableDataService,
  upLoadFiles,
} from '../../service';
// @ts-ignore
import { PLoading, TRAlert, TRMessage } from '#/components';
// @ts-ignore
import { HttpCode } from '#/utils/contacts';
import { serverUrl } from '../../../../../../../config/urlConfig';
import { downFile, havePermissions } from '../../tool';
import { connect } from 'umi';

interface IProps {
  /**
   * 数据源
   */
  dataSource?: IDataSourceType;
  /**
   * 查询数据
   */
  fetchData?: any;
  setPage?: any;
  setPageSize?: any;
  marketId?: string;
  buttonPermissions: any;
  setTableData: any;
  tableData: any;
  pages: number;
  pageSize: number;
}

const List = (props: IProps) => {
  const {
    dataSource = { columnHeaders: [], rowData: [], total: 0, page: 1, size: 10 },
    fetchData,
    marketId,
    buttonPermissions,
    setTableData,
    tableData,
    setPage,
    setPageSize,
  } = props;

  const { columnHeaders = [], total, page, size } = dataSource;
  const [editOldObj, setEditOldObj] = useState<any>({});

  const handleSave = async (row: any) => {
    const saveData: any = _.clone(row);
    // 后端要求为null字段传空字符串
    for (const key in saveData) {
      saveData[key] = saveData[key] === null ? '' : saveData[key];
    }
    // will 新增编辑保存函数
    if (row.recordId.startsWith('new-')) {
      delete saveData.recordId;
      const res = await saveMonthTableDataService({ ...saveData, marketId: marketId });
      if (res && res?.statusCode === HttpCode.SUCCESS) {
        TRMessage.success('保存成功');
        fetchData();
      } else {
        TRMessage.error(res?.message || '保存失败');
      }
    } else {
      const res = await monthTableRowEditService(saveData);
      if (res && res?.statusCode === HttpCode.SUCCESS) {
        fetchData();
        TRMessage.success('编辑成功');
      } else {
        TRMessage.error(res?.message || '编辑失败');
      }
    }
  };

  const handleCancel = (row: any) => {
    let newList = _.cloneDeep(tableData);
    newList = newList.map((i: any) =>
      i.recordId === row.recordId ? { isEdit: false, ...editOldObj[i.recordId] } : i,
    );
    setTableData(newList);
  };

  const handleDeleteRow = async (row: any) => {
    const isNewRow = row.recordId?.startsWith('new-');
    if (isNewRow) {
      const arr = tableData.filter((i: any) => i.recordId !== row.recordId);
      setTableData([...arr]);
      TRMessage.success('删除成功');
    } else {
      const resoult = havePermissions('SettlementDataDisplayMonthUpdate', buttonPermissions);
      if (resoult) {
        const obj = await TRAlert.eamDelete('请确认是否当前行？');

        if (obj?.index === 1) {
          const res = await deleteMonthTableDataService(row.recordId);
          if (res && res?.statusCode === HttpCode.SUCCESS) {
            TRMessage.success('删除成功');
            fetchData();
          } else {
            TRMessage.error(res?.message || '删除失败');
          }
        }
      }
    }
  };

  const handleEditRow = (row: any) => {
    const resoult = havePermissions('SettlementDataDisplayMonthUpdate', buttonPermissions);
    if (resoult) {
      const arr = tableData.map((i: any) => {
        if (row.recordId === i.recordId) {
          return { ...i, isEdit: true };
        } else {
          if (i.isEdit) {
            return { ...editOldObj[i.recordId], isEdit: false };
          }
          return { ...i, isEdit: false };
        }
      });
      setEditOldObj({ ...editOldObj, [row.recordId]: row });
      setTableData([...arr]);
    }
  };

  const downloadAttachment = (file: any) => {
    const _durl = `${serverUrl}/annex/annex/downLoadFile/${file.id}`;
    downFile(_durl, file.name);
  };

  const removeAttachment = (key: string, index: number, v: any) => {
    const newTableData: any = _.cloneDeep(tableData);
    newTableData[index][key] = newTableData?.[index]?.[key]?.filter((i: any) => i.id !== v.id);
    setTableData(newTableData);
  };

  // will 分页
  const onHandlePage = (p: number, ps: number) => {
    setPage(p);
    setPageSize(ps);
    fetchData({
      pages: p,
      pageSize: ps,
    });
  };

  const customRequest = async (index: number, data: any) => {
    const { fileList } = data;
    if (fileList.every((i: any) => i.status === 'uploading')) {
      PLoading.show('上传附件中...');
      const newList: any = _.cloneDeep(tableData);
      const fileKey: any = columnHeaders.find((h) => h.fieldTitle === '附件')?.id;
      const row = newList?.[index];
      const tableFileList = row?.[fileKey + ''] || [];
      const uploadService: any = [];
      // 是否名称重复
      let isRepeat = false;
      fileList.forEach((f: any) => {
        isRepeat = tableFileList.some((i: any) => i.name === f.name);
        const pdata = new window.FormData();
        pdata.append('file', f.originFileObj);
        uploadService.push(upLoadFiles(pdata));
      });
      if (isRepeat) {
        TRMessage.error('已存在文件名相同的文件!');
      } else {
        const res = await Promise.all(uploadService);
        if (res.every((s: any) => s?.statusCode === HttpCode.SUCCESS)) {
          const isNewRow = row.recordId?.startsWith('new-');
          newList[index][fileKey + ''] = newList[index]?.[fileKey + ''] || [];
          res.forEach((r: any) => {
            const { fileId, filename } = r.uploadBody;
            newList[index][fileKey + '']?.push({ id: fileId, name: filename });
          });
          // 已有数据导入
          if (!isNewRow) {
            if (!row.isEdit) {
              const newRow: any = newList[index];
              await handleSave(newRow);
            } else {
              setTableData(newList);
            }
          } else {
            // 新增情况
            setTableData(newList);
          }
          TRMessage.success('上传成功');
        } else {
          TRMessage.success('上传失败');
        }
      }
      PLoading.dismiss();
    }
  };

  const lastColumn = [
    {
      code: 'op',
      name: '操作',
      width: 200,
      render(v: string, row: any, index: number) {
        if (row.total) {
          return null;
        }
        const isEditing = !!row.isEdit;
        const isNewRow = row.recordId?.startsWith('new-');
        return (
          <div className={styles.op}>
            <>
              <Upload
                showUploadList={false}
                multiple
                fileList={[]}
                onChange={(e: any) => customRequest(index, e)}
              >
                <Button size="small" type="link">
                  导入
                </Button>
              </Upload>
              {!isNewRow && !isEditing && (
                <>
                  <Button size="small" type="link" onClick={() => handleEditRow(row)}>
                    编辑
                  </Button>
                </>
              )}
              {isNewRow && (
                <>
                  <Button size="small" type="link" onClick={() => handleSave(row)}>
                    保存
                  </Button>
                </>
              )}
              {isEditing && !isNewRow && (
                <>
                  <Button size="small" type="link" onClick={() => handleSave(row)}>
                    保存
                  </Button>
                  <Button size="small" type="link" onClick={() => handleCancel(row)}>
                    取消
                  </Button>
                </>
              )}
              <Button size="small" type="link" onClick={() => handleDeleteRow(row)}>
                删除
              </Button>
            </>
          </div>
        );
      },
    },
  ];

  // 动态生成列
  const generateColumns = () => {
    if (!columnHeaders.length) return [];
    const column = columnHeaders.map((v: any) => {
      const isWindPowerColumn = v.fieldUnits.includes('亿kWh');
      const isWindPriceColumn = v.fieldUnits.includes('元/MWh');
      if (v.fieldTitle === '附件') {
        return {
          width: 150,
          code: v.id + '',
          align: 'center',
          name: `${v?.fieldTitle || ''}`,
          render: (value: any, record: any, index: number) => {
            return (
              <div className={styles.attachment}>
                {value?.map((item: any) => (
                  <div key={item.id} style={{ display: 'flex' }}>
                    <Tooltip placement="topLeft" title={item.name}>
                      <div className={styles.text}>{item.name}</div>
                    </Tooltip>
                    <div className={styles.download}>
                      {record.isEdit ? (
                        <Button
                          type="link"
                          icon={<DeleteOutlined />}
                          style={{ color: '#FF5757' }}
                          size="small"
                          onClick={() => removeAttachment(v.id, index, item)}
                        />
                      ) : (
                        <Button
                          type="link"
                          icon={<DownloadOutlined />}
                          size="small"
                          onClick={() => downloadAttachment(item)}
                        />
                      )}
                    </div>
                  </div>
                ))}
              </div>
            );
          },
        };
      } else {
        const name = (
          <div>
            <div>{v?.fieldTitle || ''}</div>
            <div>{v?.fieldUnits ? `(${v?.fieldUnits})` : ''}</div>
          </div>
        );
        return {
          code: v.id + '',
          width: 120,
          name: name,
          align: 'center',
          render: (value: any, record: any) => {
            if (record.isEdit) {
              if (v.fieldTitle === '备注') {
                return (
                  <Input.TextArea
                    className={styles.inputBox}
                    placeholder="请输入"
                    maxLength={500}
                    defaultValue={value}
                    onChange={(e) => {
                      let newTableData = _.cloneDeep(tableData);
                      newTableData = newTableData.map((i: any) =>
                        i.recordId === record.recordId ? { ...i, [v.id]: e.target.value } : i,
                      );
                      setTableData(newTableData);
                    }}
                  />
                );
              } else if (v.fieldTitle === '月份') {
                return (
                  <Input
                    className={styles.inputBox}
                    placeholder="请输入"
                    defaultValue={value}
                    onChange={(e) => {
                      let newTableData = _.cloneDeep(tableData);
                      newTableData = newTableData.map((i: any) =>
                        i.recordId === record.recordId ? { ...i, [v.id]: e.target.value } : i,
                      );
                      setTableData(newTableData);
                    }}
                  />
                );
              } else {
                return (
                  <InputNumber
                    className={styles.inputBox}
                    placeholder="请输入"
                    precision={3} // 限制最多3位小数
                    defaultValue={value}
                    onChange={(e) => {
                      let newTableData = _.cloneDeep(tableData);
                      newTableData = newTableData.map((i: any) =>
                        i.recordId === record.recordId ? { ...i, [v.id]: e + '' } : i,
                      );
                      setTableData(newTableData);
                    }}
                  />
                );
              }
            } else {
              return (
                <Tooltip title={value}>
                  <div className={styles.text}>{value}</div>
                </Tooltip>
              );
            }
          },
          getCellProps: (value: any, row: any, index: number) => {
            const isLastRow = row.total;
            if (isLastRow) {
              if (isWindPowerColumn) {
                return { colSpan: 2 };
              }
              if (isWindPriceColumn) {
                return { colSpan: 0 };
              }
            }
            return { colSpan: 1 };
          },
        };
      }
    });
    return [...column, ...lastColumn];
  };

  const columns = generateColumns();

  const pipeline = useTablePipeline({})
    .input({ dataSource: tableData, columns: columns as any })
    .primaryKey('recordId')
    .appendRowPropsGetter((): any => {
      const color = '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  return (
    <div className={`${styles.container}`}>
      <div className={styles.tableBox}>
        <AntdBaseTable
          useVirtual={{ horizontal: true, vertical: true, header: false }}
          style={{
            '--row-height': '28px',
            '--header-row-height': '28px',
            '--cell-padding': '4px 16px',
            '--cell-border-vertical': '1px solid #4E5154',
            '--header-cell-border-vertical': '1px solid #4E5154',
            '--hover-bgcolor': '#222629',
          }}
          {...pipeline.getProps()}
        />
      </div>

      <div style={{ marginTop: 12, textAlign: 'right' }}>
        <Pagination
          current={page}
          pageSize={size}
          total={total}
          onChange={(p, ps) => {
            onHandlePage(p, ps || 10);
          }}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
        />
      </div>
    </div>
  );
};

export default connect(({ global }: any) => ({
  buttonPermissions: global.configure.buttonPermissions,
}))(List);
